"""
管理员相关路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr
from typing import List, Optional

from backend.app.db.database import get_db
from backend.app.db.operations import verification,  user_ops

router = APIRouter(prefix="/admin", tags=["管理员"])

class AdminInfo(BaseModel):
    """管理员信息模型"""
    email: EmailStr
    code: str
    nickname: str = None
    avatar: str = None

class UserCreate(BaseModel):
    """创建用户请求模型"""
    email: EmailStr
    nickname: str = None
    avatar: str = None
    is_admin: bool = False

class UserResponse(BaseModel):
    """用户响应模型"""
    email: str
    nickname: Optional[str] = None
    avatar: Optional[str] = None
    is_admin: bool = False
    created_at: str

@router.get("/dashboard")
async def admin_dashboard(
    email: EmailStr,
    code: str,
    db: Session = Depends(get_db)
):
    """
    管理员仪表板
    """
    # 验证邮箱验证码
    if not verification.verify_code(db, email, code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 验证是否为管理员
    admin = user_ops.get_user_by_email(db, email)
    if not admin or not admin.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问"
        )
    
    # 获取仪表板数据
    stats = user_ops.get_dashboard_stats(db)
    return {
        "message": "获取仪表板数据成功",
        "data": stats
    }

@router.get("/users")
async def list_users(
    email: EmailStr,
    code: str,
    skip: int = 0,
    limit: int = 10,
    db: Session = Depends(get_db)
):
    """
    获取所有用户列表
    """
    # 验证邮箱验证码
    if not verification.verify_code(db, email, code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 验证是否为管理员
    admin = user_ops.get_user_by_email(db, email)
    if not admin or not admin.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问"
        )
    
    # 获取用户列表
    users = user_ops.get_users(db, skip, limit)
    total = db.query(user_ops.User).count()
    
    return {
        "message": "获取用户列表成功",
        "data": {
            "total": total,
            "users": [
                {
                    "email": user.email,
                    "nickname": user.nickname,
                    "avatar": user.avatar,
                    "is_admin": user.is_admin,
                    "created_at": user.created_at.isoformat()
                }
                for user in users
            ]
        }
    }

@router.post("/users")
async def create_user(
    user: UserCreate,
    admin_email: EmailStr,
    admin_code: str,
    db: Session = Depends(get_db)
):
    """
    创建新用户
    """
    # 验证管理员邮箱验证码
    if not verification.verify_code(db, admin_email, admin_code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 验证是否为管理员
    admin = user_ops.get_user_by_email(db, admin_email)
    if not admin or not admin.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问"
        )
    
    # 检查用户是否已存在
    if user_ops.get_user_by_email(db, user.email):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该邮箱已被注册"
        )
    
    # 创建用户
    new_user = user_ops.create_user(
        db,
        email=user.email,
        nickname=user.nickname,
        avatar=user.avatar,
        is_admin=user.is_admin
    )
    
    return {
        "message": "创建用户成功",
        "data": {
            "email": new_user.email,
            "nickname": new_user.nickname,
            "avatar": new_user.avatar,
            "is_admin": new_user.is_admin
        }
    }

@router.put("/users/{user_email}")
async def update_user(
    user_email: EmailStr,
    user_info: UserCreate,
    admin_email: EmailStr,
    admin_code: str,
    db: Session = Depends(get_db)
):
    """
    更新用户信息
    """
    # 验证管理员邮箱验证码
    if not verification.verify_code(db, admin_email, admin_code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 验证是否为管理员
    admin = user_ops.get_user_by_email(db, admin_email)
    if not admin or not admin.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问"
        )
    
    # 更新用户信息
    updated_user = user_ops.update_user(
        db,
        email=user_email,
        nickname=user_info.nickname,
        avatar=user_info.avatar,
        is_admin=user_info.is_admin
    )
    
    if not updated_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return {
        "message": "更新用户成功",
        "data": {
            "email": updated_user.email,
            "nickname": updated_user.nickname,
            "avatar": updated_user.avatar,
            "is_admin": updated_user.is_admin
        }
    }

@router.delete("/users/{user_email}")
async def delete_user(
    user_email: EmailStr,
    admin_email: EmailStr,
    admin_code: str,
    db: Session = Depends(get_db)
):
    """
    删除用户
    """
    # 验证管理员邮箱验证码
    if not verification.verify_code(db, admin_email, admin_code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 验证是否为管理员
    admin = user_ops.get_user_by_email(db, admin_email)
    if not admin or not admin.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问"
        )
    
    # 删除用户
    if not user_ops.delete_user(db, user_email):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return {
        "message": "删除用户成功",
        "data": {
            "email": user_email
        }
    } 